package com.guoxin.part1.chapter5;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.IntFunction;
import java.util.stream.IntStream;

/**
 * @author guoxin
 * @date 2019/8/28
 */
public class BooleanLockClient {

    private final Lock lock = new BooleanLock();

    public void syncMethod() {
        try {
            lock.lock();
            int randomInt = ThreadLocalRandom.current().nextInt(10);
            System.out.println(Thread.currentThread() + " get the lock.");
            TimeUnit.SECONDS.sleep(randomInt);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void syncMethodTiemoutable() {
        try {
            lock.lock(1000);
            System.out.println(Thread.currentThread() + " get the lock.");
            int randomInt = ThreadLocalRandom.current().nextInt(10);
            TimeUnit.SECONDS.sleep(randomInt);
        } catch (InterruptedException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BooleanLockClient client = new BooleanLockClient();
        //        IntStream.range(0,10).mapToObj(value -> new Thread(client::syncMethod)).forEach(Thread::start);

        //        new Thread(client::syncMethod, "T1").start();
        //        TimeUnit.MILLISECONDS.sleep(2);
        //        Thread t2 = new Thread(client::syncMethod, "T2");
        //        t2.start();
        //        TimeUnit.MILLISECONDS.sleep(10);
        //        t2.interrupt();

        new Thread(client::syncMethod, "T1").start();
        TimeUnit.MILLISECONDS.sleep(2);
        Thread t2 = new Thread(client::syncMethodTiemoutable, "T2");
        t2.start();
        TimeUnit.MILLISECONDS.sleep(10);
    }
}
